<!--
 * @Author: wuzhen
 * @Date: 2020-01-14 13:20:44
 * @LastEditors: wuzhen
 * @LastEditTime: 2020-04-16 15:31:15
 * @Description: 头部注释
 -->
<template>
  <div class="chat-tool">
    <div class="tool-box">
      <div class="icon-emoj icon-img" :class="{'disabled': chatInfo.msgkind === 30 && chatInfo.syssetting.toString(2).indexOf('1') === 0}" @click.stop="openEmoj">
        <img :src="icon_emoj" />
      </div>
      <div class="icon-doc icon-img" :class="{'disabled': chatInfo.msgkind === 30 && chatInfo.syssetting.toString(2).indexOf('1') === 0}">
        <Upload style="display:flex" ref="upload" :action="`${baseUrl}/upload/shareFiles`" :headers="uploadHeaders" :disabled="chatInfo.msgkind === 30 && chatInfo.syssetting.toString(2).indexOf('1') === 0" :show-upload-list="false" :before-upload="handleBeforeUpload" :on-progress="handleProgress" :on-success="handleSuccess">
          <img :src="icon_doc" />
        </Upload>
      </div>
      <div class="icon-recall icon-img" :class="{'disabled': chatInfo.msgkind === 30 && chatInfo.syssetting.toString(2).indexOf('1') === 0}" @click.stop="onRecall">
        <img :src="icon_recall" />
      </div>
    </div>
    <at-ta ref="atTa" :members="members" style="flex:auto" @keyup.native.enter.exact="onSendText">
      <textarea class="editor" v-model="content" :disabled="chatInfo.msgkind === 30 && chatInfo.syssetting.toString(2).indexOf('1') === 0" :placeholder="chatInfo.msgkind === 30 && chatInfo.syssetting.toString(2).indexOf('1') === 0?$t('chat_forbidden'):''"></textarea>
    </at-ta>
    <div class="send-btn">
      <Button disabled v-if="chatInfo.msgkind === 30 && chatInfo.syssetting.toString(2).indexOf('1') === 0">{{$t("btn_sendMsg")}}</Button>
      <Button class="custom" @click.stop="onSendText" v-else>{{$t("btn_sendMsg")}}</Button>
    </div>
    <Modal v-model="showModel" width="360" :styles="{top:'40%'}">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>{{$t("two_recall")}}</span>
      </p>
      <div style="text-align:center">
        <p>{{$t("tip_recall")}}</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long @click.stop="onSubmit">{{$t("btn_confirm")}}</Button>
      </div>
    </Modal>
    <!-- 表情弹框 -->
    <div class="emoj-Model" v-if="showEmoj" v-click-outside="() => {showEmoj = false}">
      <div class="emoj-icon" v-for="(item, index) in emojs" :key="index" @click.stop="onSendEmoj(item.name)">
        <img :src="item.filename" :alt="item.name" :title="item.name">
      </div>
    </div>
    <!-- 文件上传弹窗 -->
    <Modal v-model="showFile" width="440" class-name="fileModal">
      <p slot="header" style="text-align:center">
        <span>{{file.iconType==='image'?$t("send_picture"):$t("send_file")}}</span>
      </p>
      <div style="text-align:center">
        <div class="file-box" v-if="showFile">
          <img :src="require(`@/assets/image/file/${file.iconType}.png`)" v-if="file.iconType!=='image'" class="file-icon">
          <img :src="file.img" v-else>
        </div>
        <p class="file-name">{{file.name}}</p>
        <p class="file-size">{{file.sizeStr}}</p>
      </div>
      <div slot="footer" style="width: 100px;margin: 0 auto;">
        <Button type="primary" long @click.stop="onUpload">{{$t("btn_sendMsg")}}</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { Input, Button, Modal, Icon, Upload } from "view-design";
import emojs from "@/assets/Chat_Faces";
import { formatFileType, renderSize } from "@/libs/units";
import AtTa from "vue-at/dist/vue-at-textarea";
export default {
  components: { Input, Button, Modal, Icon, Upload, AtTa },
  data() {
    return {
      icon_emoj: require("@/assets/image/icon_emoj.png"),
      icon_doc: require("@/assets/image/icon_doc.png"),
      icon_recall: require("@/assets/image/icon_recall.png"),
      content: "",
      showModel: false,
      showEmoj: false,
      baseUrl: process.env.VUE_APP_BASEURL + "/wpipes",
      uploadHeaders: {
        jsessionid: this.$store.state.chat.jsessionId,
        UNF: this.$store.state.chat.unf
      },
      showFile: false,
      file: {
        iconType: "default",
        img: "",
        sizeStr: ""
      },
      fileImg: require("@/assets/image/file/default.png")
    };
  },
  computed: {
    members() {
      let members = [];
      if (this.chatting.msgkind !== 30) {
        return [];
      }
      const currentGroup = this.groups.find(v => v.id === this.chatting.id);
      if (currentGroup.groupMember && currentGroup.groupMember.length) {
        members = ["所有人"];
        currentGroup.groupMember.forEach(v => {
          if (v.userid !== this.userInfo.userid) {
            const name =
              currentGroup.grouptype === 20
                ? this.$t("anonymous") + this.$t("user") + v.annoyindex
                : v.usernickname;
            members.push(name);
          }
        });
      }
      return members;
    },
    chatInfo() {
      if (this.chatting.msgkind === 30) {
        return this.groups.find(v => v.id === this.chatting.id);
      } else if (this.chatting.msgkind === 20) {
        return this.friends.find(v => v.id === this.chatting.id);
      } else {
        return this.chatting;
      }
    },
    emojs() {
      return emojs;
    }
  },
  watch: {
    chatInfo() {
      this.content = "";
    },
    content(newValue) {
      if (!/[@]$/.test(newValue)) {
        this.$refs["atTa"].closePanel();
      }
      if (!this.isInput && this.chatInfo.msgkind === 20) {
        this.isInput = true;
        this.sendMsg({
          msgtype: 2021,
          content: {
            status: 10
          }
        });
        setTimeout(() => {
          this.isInput = false;
        }, 3000);
      }
    }
  },
  methods: {
    // 表情显示
    openEmoj() {
      if (
        this.chatInfo.msgkind === 30 &&
        this.chatInfo.syssetting.toString(2).indexOf("1") === 0
      )
        return;
      this.showEmoj = true;
    },
    // 一键撤回
    onRecall() {
      if (
        this.chatInfo.msgkind === 30 &&
        this.chatInfo.syssetting.toString(2).indexOf("1") === 0
      )
        return;
      this.showModel = true;
    },
    // 确定撤回
    onSubmit() {
      const array1 = this.chatMsg.filter(v => v.id === this.chatting.id);
      if (!array1.length) {
        this.showModel = false;
        return;
      }
      const msg = encodeURIComponent(
        JSON.stringify({
          targetid: this.chatting.id,
          msgkind: this.chatting.msgkind,
          msgtype: 2017,
          content: JSON.stringify({
            targetid: this.chatting.id,
            starttime: array1[0].createtime
          })
        })
      );
      this.$imWebSocket.sendMsg(msg);
      let array = [];
      if (
        this.chatInfo.createuserid === this.userInfo.userid ||
        this.chatInfo.msgkind === 20
      ) {
        array = this.chatMsg.filter(v => v.id !== this.chatInfo.id);
      } else {
        array = this.chatMsg.filter(
          v => v.fromid !== this.userInfo.userid && v.id === this.chatInfo.id
        );
      }
      this.set_chatMsg(array);
      this.chatUsers.forEach(v => {
        if (v.id === this.chatting.id) {
          v.content = "";
        }
      });
      this.set_chatUsers(this.chatUsers);
      this.showModel = false;
    },
    // 上传文件之前的钩子
    handleBeforeUpload(file) {
      this.file = file;
      const iconType = formatFileType(file.name);
      this.file["iconType"] = iconType;
      this.file["sizeStr"] = renderSize(file.size);
      if (iconType === "image") {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = async () => {
          this.file["img"] = reader.result;
          this.showFile = true;
        };
      } else {
        this.showFile = true;
      }
      return false;
    },
    // 确定上传
    onUpload() {
      const http_seqno = new Date().getTime();
      this.messageid = `${this.userInfo.userid}-${
        this.chatting.id
      }-${http_seqno.toString(36)}`;
      const obj = {
        content: {
          name: this.file["name"],
          size: this.file["size"],
          type: this.file["iconType"],
          fileUrl: this.file["img"],
          content:
            this.file["iconType"] === "image"
              ? `[${this.$t("picture")}]`
              : `[${this.$t("file")}]`
        },
        targetid: this.chatting.id,
        msgkind: this.chatting.msgkind,
        msgtype: this.file["iconType"] === "image" ? 1010 : 1003,
        createtime: http_seqno,
        messageid: this.messageid,
        fromid: this.userInfo.userid,
        id: this.chatting.id,
        isRead: true,
        percent: 0,
        msgStatus: 0
      };
      this.chatMsg.push(obj);
      this.set_chatMsg(this.chatMsg);
      this.showFile = false;
      this.$refs["upload"].post(this.file);
    },
    // 进行中
    handleProgress(e) {
      this.chatMsg.forEach(v => {
        if (v.messageid === this.messageid) {
          v.percent = e.percent === 100 ? 93 : e.percent;
        }
      });
      this.set_chatMsg(this.chatMsg);
    },
    //  文件上传成功时的钩子
    handleSuccess(res) {
      const fileUrl = `http://api.butter.im/wpipes/dir/shareFiles/${res.result[0].fileid}`;
      const currentIndex = this.chatMsg.findIndex(
        v => v.messageid === this.messageid
      );
      const obj = {
        targetid: this.chatting.id,
        msgkind: this.chatting.msgkind,
        msgtype: this.chatMsg[currentIndex].msgtype,
        createtime: this.chatMsg[currentIndex].createtime,
        messageid: this.chatMsg[currentIndex].messageid,
        content: JSON.stringify({
          ...this.chatMsg[currentIndex].content,
          ...{
            fileUrl: fileUrl,
            thumbnailUrl: fileUrl
          }
        })
      };
      this.chatMsg.forEach(v => {
        if (v.messageid === this.messageid) {
          v.percent = 100;
          v.content["fileUrl"] = fileUrl;
          v.content["thumbnailUrl"] = fileUrl;
        }
      });
      this.set_chatMsg(this.chatMsg);
      const msg = encodeURIComponent(JSON.stringify(obj));
      this.$imWebSocket.sendMsg(msg, this.chatMsg[currentIndex].createtime);
    },
    // 发送文本消息
    onSendText() {
      if (!this.content.trim() || /[@]$/.test(this.content)) return;
      const msg = {
        msgtype: 1001,
        content: {
          content: this.content.replace(/\n$/gi, "")
        }
      };
      if (this.chatInfo.msgkind === 30) {
        // 判断是否@
        const mentionedType = this.content.includes("@所有人 ");
        const currentGroup = this.groups.find(v => v.id === this.chatting.id);
        const users = currentGroup.groupMember.filter(v =>
          this.content.includes(
            `@${
              currentGroup.grouptype === 20
                ? this.$t("anonymous") + this.$t("user") + v.annoyindex
                : v.usernickname
            } `
          )
        );
        const userIds = users.map(v => {
          return v.userid;
        });
        if (mentionedType || userIds.length) {
          msg["mentionedInfo"] = {
            type: mentionedType ? 1 : 2, // 1 表示 @ 所有人、2 表示 @ 指定用户列表
            userIds: userIds // 指定用户列表，type 为 2 时有效
          };
        }
      }
      this.sendMsg(msg);
      this.showEmoj = false;
      this.content = "";
    },
    // 发送表情
    onSendEmoj(emoj) {
      this.content = this.content + `[${emoj}]`;
    },
    // socket发送消息
    sendMsg({ msgtype = null, content = {}, mentionedInfo = null }) {
      const http_seqno = new Date().getTime();
      const obj = {
        targetid: this.chatting.id,
        msgkind: this.chatting.msgkind,
        msgtype: msgtype,
        createtime: http_seqno,
        messageid: `${this.userInfo.userid}-${
          this.chatting.id
        }-${http_seqno.toString(36)}`,
        content: JSON.stringify(content)
      };
      if (mentionedInfo) {
        obj["mentionedInfo"] = mentionedInfo;
      }
      const msg = encodeURIComponent(JSON.stringify(obj));
      if (msgtype !== 2021) {
        // 存储到本地
        this.chatMsg.push({
          ...obj,
          ...{
            content: content,
            fromid: this.userInfo.userid,
            id: this.chatting.id,
            isRead: true,
            msgStatus: 0
          }
        });
        this.set_chatMsg(this.chatMsg);
      } else {
        this.set_input_httpSeqno(http_seqno);
      }
      this.$imWebSocket.sendMsg(msg, http_seqno);
    }
  }
};
</script>

<style lang="less">
.chat {
  &-tool {
    height: 135px;
    position: relative;
    padding: 10px;
    display: flex;
    flex-direction: column;
    border-top: 1px solid #e1e3e8;
    .tool-box {
      display: flex;
      margin-bottom: 5px;
      .icon-img {
        margin: 0 8px;
        cursor: pointer;
        &.disabled {
          cursor: not-allowed;
          opacity: 0.3;
        }
        img {
          width: 20px;
          height: 20px;
        }
      }
    }
    .editor {
      height: 100%;
      width: 100%;
      border: none;
      resize: none;
      background: none;
      padding: 0 10px;
      box-sizing: border-box;
      &:disabled {
        color: #999;
      }
      &:focus {
        border: none;
        outline: none;
        box-shadow: none;
      }
    }
    .send-btn {
      padding: 10px 0 0;
      text-align: right;
      .custom {
        background: #fff;
        color: #f8a42b;
        width: 90px;
        height: 30px;
        line-height: 30px;
        font-size: 14px;
        border-radius: 4px;
        border: 1px solid #e1e3e8;
      }
    }
    .emoj-Model {
      position: fixed;
      left: 250px;
      bottom: 130px;
      width: 490px;
      background: #fff;
      border: 1px solid #eee;
      box-shadow: 0 0px 1px rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      padding: 10px;
      .emoj-icon {
        display: inline-block;
        margin: 3px;
        img {
          cursor: pointer;
          width: 30px;
          height: 30px;
        }
      }
    }
  }
}
.fileModal {
  .file {
    &-box {
      text-align: center;
      img {
        display: inline-block;
        max-width: 100%;
      }
    }
    p {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-wrap: normal;
    }
    &-icon {
      display: inline-block;
      box-sizing: border-box;
      height: 125px;
    }
    &-img {
      max-width: 100%;
      max-height: 200px;
    }
    &-name {
      margin-top: 10px;
    }
    &-size {
      margin-top: 10px;
      color: #7d7d7e;
    }
  }
}
</style>
